package com.wu.client.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.wu.client.constant.ResTypeEnum;

import com.wu.client.dao.redis.Likes;
import com.wu.client.service.ReplyCommentsService;
import com.wu.client.service.UserLikesService;
import com.wu.client.utils.DateUtil;
import com.wu.client.utils.PageRespUtil;
import com.wu.client.vo.req.comment.CommentReplyReq;
import com.wu.client.vo.res.PageResp;
import com.wu.client.vo.res.comment.ReplyCommentAddResp;
import com.wu.client.vo.res.comment.ReplyCommentResp;
import com.wu.mongo.ReplyComment;
import com.wu.mysql.entiy.UserDO;
import com.wu.mysql.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class ReplyCommentsServiceImpl  implements ReplyCommentsService {
    private final MongoTemplate mongoTemplate;
    private final UserLikesService userLikesService;
    private final UserMapper userMapper;
    @Override
    public PageResp<ReplyCommentResp> getReplyInPage(Long userId, String parentId, Integer page, Integer limit) {
        Query query = new Query();
        PageRequest pageRequest = PageRequest.of(page -1, limit, Sort.by(Sort.Order.asc("createdAt")));
        query.addCriteria(Criteria.where("parentId").is(new ObjectId(parentId)));
        query.with(pageRequest);
        long totalCount = mongoTemplate.count(query, ReplyComment.class);
        List<ReplyComment> results = mongoTemplate.find(query, ReplyComment.class);  // 查询结果
        if (CollectionUtil.isNotEmpty(results)) {
            Set<Long> userIds = new HashSet<>();
            List<ObjectId> resIds = new ArrayList<>(results.size());
            results.forEach(comment -> {
                userIds.add(comment.getUserId());
                userIds.add(comment.getReplyUserId());
                resIds.add(comment.getId());
            });
            // 查询用户点赞信息
            Map<ObjectId, Likes> ifLike = userLikesService.checkUserIfLike(ResTypeEnum.COMMENT, userId, resIds);
            // 查询用户资料
            List<UserDO> userDOS = userMapper.selectBatchIds(userIds);
            Map<Long, UserDO> userMap = userDOS.stream().collect(Collectors.toMap(UserDO::getId, userDO -> userDO));
            // 转换评论数据
            List<ReplyCommentResp> replyCommentRespList = results.stream().map(comment -> {
                ReplyCommentResp resp = BeanUtil.copyProperties(comment, ReplyCommentResp.class);
                resp.setCreatedAt(DateUtil.format(comment.getCreatedAt()));
                UserDO userDO = userMap.get(comment.getUserId());
                if (ObjectUtil.isNotNull(userDO)) {
                    resp.setUsername(userDO.getUsername());
                    resp.setAvatar(userDO.getAvatar());
                    resp.setUserId(userDO.getId());
                }
                UserDO replyUser = userMap.get(comment.getReplyUserId());
                resp.setReplyToUsername(replyUser != null ? replyUser.getUsername() : null);
                // 获取评论的点赞信息
                Likes likes = ifLike.get(comment.getId());
                if (ObjectUtil.isNotNull(likes)) {
                    resp.setLikeCount(likes.getCount());
                    resp.setIsLiked(likes.getIsLiked());
                }
                return resp;
            }).collect(Collectors.toList());
            return PageRespUtil.buildPageResp(page, limit, totalCount, replyCommentRespList);
        }
        return new PageResp<>();
    }

    @Override
    public ReplyCommentAddResp addReply(CommentReplyReq commentReplyReq, String parentId) {
        Date now =new Date();
        ReplyComment replyComment = new ReplyComment();
        replyComment.setParentId(new ObjectId(parentId));
        replyComment.setContent(commentReplyReq.getContent());
        replyComment.setUserId(commentReplyReq.getUserId());
        replyComment.setCreatedAt(now);
        replyComment.setReplyUserId(commentReplyReq.getReplyUserId());
        mongoTemplate.save(replyComment);
        ReplyCommentAddResp replyCommentAddResp = BeanUtil.copyProperties(replyComment, ReplyCommentAddResp.class,"createdAt");
        replyCommentAddResp.setCreatedAt(DateUtil.format(now));
        return replyCommentAddResp;
    }

    @Override
    public void deleteReply(String replyId) {
        mongoTemplate.remove(new Query(Criteria.where("id").is(new ObjectId(replyId))), ReplyComment.class);
    }
}
